package org.makcro.sms.services.chat.base.filters;

import java.text.MessageFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.makcro.sms.services.chat.base.dao.BulkMessageDao;
import org.makcro.sms.services.chat.base.service.ResponseReport;
import org.makcro.sms.services.chat.base.service.SMSChatServiceImpl;
import org.makcro.sms.services.chat.model.BulkMessage;

import com.klikmee.sms.core.commons.filters.ProcessItemFilter;

/**
 * Impl of {@link ProcessItemFilter} intended to handle bulk message response
 * reports
 * 
 * @author makcro
 * 
 */
public class BulkMessageResponseReportFilterImpl implements ProcessItemFilter<ResponseReport> {

	// logger instance
	private Logger			logger	= Logger.getLogger( BulkMessageResponseReportFilterImpl.class );

	private BulkMessageDao	bulkMessageDao;

	/**
	 * Tries to resolve response report to bulk message. If resolved updates
	 * bulk messages delivery report and update date.
	 */
	@Override
	public boolean process(ResponseReport item) {
		// try to find bulk message by core id
		Long coreId = item.getCoreId();
		BulkMessage bulkMessage = this.bulkMessageDao.findByCoreId( coreId );

		if (bulkMessage != null) {
			// if bulk message is found by core id, update it's status
			boolean messageDelivered = SMSChatServiceImpl.ANSWER_DELIVERED.equals( item.getStatus() ) ? true : false;
			bulkMessage.setDelivered( messageDelivered );
			bulkMessage.setDeliveryReportDate( new Date() );

			this.bulkMessageDao.edit( bulkMessage );

			logger.info( MessageFormat.format( "Updated delivery report of bulk message [{0}] to [{1}]", bulkMessage, item.getStatus() ) );
			return true;
		}
		logger.debug( MessageFormat.format( "Could not resolve core id [{0}] to any bulk message", coreId ) );
		return false;
	}

	public void setBulkMessageDao(BulkMessageDao bulkMessageDao) {
		this.bulkMessageDao = bulkMessageDao;
	}

}
